package org.jeecg.modules.controller.order;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.jeecg.common.modules.dic.service.IDicBeGoodAtService;
import org.jeecg.common.modules.doctor.entity.Doctor;
import org.jeecg.common.modules.doctor.entity.DoctorRegister;
import org.jeecg.common.modules.doctor.entity.DoctorRegisterOperate;
import org.jeecg.common.modules.doctor.entity.DoctorRegisterRecord;
import org.jeecg.common.modules.doctor.service.*;
import org.jeecg.common.modules.doctor.vo.DoctorRegisterRecordSysListVo;
import org.jeecg.common.modules.makeAppointment.entity.MakeAppointment;
import org.jeecg.common.modules.makeAppointment.entity.MakeAppointmentInfo;
import org.jeecg.common.modules.makeAppointment.service.IMakeAppointmentInfoService;
import org.jeecg.common.modules.makeAppointment.service.IMakeAppointmentService;
import org.jeecg.common.modules.order.entity.OrderInfo;
import org.jeecg.common.modules.order.service.IOrderInfoService;
import org.jeecg.common.modules.order.service.IPayOrderService;
import org.jeecg.common.modules.register.entity.RegisterPatient;
import org.jeecg.common.modules.register.entity.RegisterPayOrder;
import org.jeecg.common.modules.register.service.IRegisterPatientService;
import org.jeecg.common.modules.register.service.IRegisterPayOrderService;
import org.jeecg.common.modules.registerRefoundAudit.entity.RegisterRefoundAudit;
import org.jeecg.common.modules.registerRefoundAudit.service.IRegisterRefoundAuditService;
import org.jeecg.common.modules.wx.entity.WxUserinfo;
import org.jeecg.common.modules.wx.service.IWxUserinfoService;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.DySmsEnum;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.enums.RegisterEnum;
import org.jeecg.common.util.result.Result;
import org.jeecg.common.util.result.ResultMapper;
import org.jeecg.common.wx.WxRefundService;
import org.jeecg.modules.controller.BaseController;
import org.jeecg.modules.controller.notify.WeixinUtil;
import org.jeecg.modules.service.ApiOrderService;
import org.jeecg.modules.service.DySendMsg;
import org.jeecg.modules.vo.request.PrePayOrderRequestVo;
import org.jeecg.modules.vo.respone.PrePayOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.weixin4j.model.pay.WCPay;
import org.weixin4j.spring.WeixinTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author guoyh
 * @ClassName OrderController
 * @Description
 * @since 2020/8/29 01:54
 **/
@Slf4j
@RestController
@RequestMapping("api/v1/order")
public class OrderController extends BaseController {

    @Resource
    private ApiOrderService apiOrderService;
    @Resource
    private RedisUtil redisUtil;
    @Autowired
    private IMakeAppointmentInfoService iMakeAppointmentInfoService;
    @Resource
    private WeixinTemplate weixinTemplate;
    @Resource
    private IOrderInfoService orderService;
    @Resource
    private IPayOrderService payOrderService;
    @Resource
    private WxRefundService wxRefundService;
    @Resource
    private IRegisterPayOrderService registerPayOrderService;
    @Resource
    private IDoctorRegisterRecordService doctorRegisterRecordService;
    @Resource
    private IWxUserinfoService wxUserinfoService;
    @Autowired
    private IRegisterRefoundAuditService registerRefoundAuditService;
    @Autowired
    private IDoctorService doctorService;
    @Autowired
    private IRegisterPatientService registerPatientService;
    @Autowired
    private IMakeAppointmentService makeAppointmentService;
    @Resource
    private IDicBeGoodAtService dicBeGoodAtService;
    @Resource
    private IDoctorRegisterHospitalService doctorRegisterHospitalService;
    @Resource
    private IDoctorRegisterOperateService doctorRegisterOperateService;
    @Resource
    private IDoctorRegisterService doctorRegisterService;
    /**
     * 公众号支付
     * @param request
     * @return
     */

    @PostMapping("prePay")
    public Result<PrePayOrderResponseVo> prePay(@RequestBody PrePayOrderRequestVo request,
                                                HttpServletRequest req, HttpServletResponse response) throws IOException {
        String openid = request.getOpenid();
        String apid = request.getApid();
        String registerRecordId = request.getRegisterRecordId();
        log.info("apid：{}",apid);
        if(apid != ""&& apid != null){
            MakeAppointment makeAppointment = makeAppointmentService.getById(apid);
            makeAppointment.setStatus("1");
            if(makeAppointment.getSurplus() == 0){
                return ResultMapper.<PrePayOrderResponseVo>error().setMsg("号源不足！");
            }
//            makeAppointment.setSurplus(makeAppointment.getSurplus()-1);
            makeAppointment.setMedicalId(request.getMedicalId());
            makeAppointmentService.updateById(makeAppointment);
            request.setApid(apid);



//            MakeAppointmentInfo makeAppointmentInfo = iMakeAppointmentInfoService.getById(apid);
//            makeAppointmentInfo.setStatus(1);
//            makeAppointmentInfo.setOpenid(openid);
//            iMakeAppointmentInfoService.updateById(makeAppointmentInfo);
        }
        return apiOrderService.prePay(request,openid,registerRecordId);
    }
    /**
     * 挂号单审核操作
     */
    @PostMapping(value = "/examine")
    public org.jeecg.common.api.vo.Result<?> examine(@RequestBody DoctorRegisterRecordSysListVo requestVo) throws ClientException, ParseException {
        //【一】发送短信
        JSONObject jsonObject = new JSONObject();
        //组织医院科室信息
        String depart = "";
        String departEnd = requestVo.getDepartmentName().substring(requestVo.getDepartmentName().length() - 1);
        if(departEnd.equals("科")){
            depart = requestVo.getDepartmentName().substring(0,requestVo.getDepartmentName().length() - 1);
        }else{
            depart = requestVo.getDepartmentName();
        }

        //处理日期
        Date visitTime = new SimpleDateFormat("yyyy-MM-dd").parse(requestVo.getVisitTime());
        String visitTimeStr = new SimpleDateFormat("yyyy年MM月dd日").format(visitTime);
        String url = "";
        if(requestVo.getStatus() == RegisterEnum.SUCCESS.getCode()){  //挂号成功
            jsonObject.put("name_1",requestVo.getPatientName());

            jsonObject.put("hospital_ment",requestVo.getHospitalName() + " " +requestVo.getDepartmentName()); //xx医院xx科室
            jsonObject.put("name_title",requestVo.getDoctorName()+"("+requestVo.getTitle()+")");  //xx医生xx职位
            jsonObject.put("date_part",visitTimeStr + " " + requestVo.getVisitPart());  //xx日期xx时间段
            jsonObject.put("num","以当天取号顺序为主，取号时间为：上午：8:00-10:00、下午：13:00-15:00、晚上：18：00-19:00");  //就诊序号
            jsonObject.put("hospital_2",requestVo.getHospitalAddress());  //医院地址0
            jsonObject.put("phone_1",requestVo.getHospitalPhone());   //医院联系电话
            if (CommonUtils.IS_ZS){
                url = "https://zzt.weixin.dyzh120.com/invite-govNew/";
            }
            //暂时注释
//            WeixinUtil.pushRegisterSuccess(requestVo.getId(),requestVo.getPatientName(),requestVo.getHospitalName() + " " +requestVo.getDepartmentName(), requestVo.getDoctorName()+"("+requestVo.getTitle()+")", visitTimeStr + " " + requestVo.getVisitPart(), requestVo.getHospitalAddress(), "以当天取号顺序为主，取号时间为：上午：8:00-10:00、下午：13:00-15:00、晚上：18：00-19:00",url);

        }else if(requestVo.getStatus() == RegisterEnum.FAIL.getCode()){  //挂号失败
            jsonObject.put("name",requestVo.getPatientName());
            jsonObject.put("hospital_department",requestVo.getHospitalName() + " " +requestVo.getDepartmentName());
            jsonObject.put("doctor",requestVo.getDoctorName());
            jsonObject.put("date_part",visitTimeStr + " " + requestVo.getVisitPart());
            jsonObject.put("phone_2",requestVo.getHospitalPhone());
            if (CommonUtils.IS_ZS){
                 url = "https://zzt.weixin.dyzh120.com/invite-govNew/";
            }
            //暂时注释
//            WeixinUtil.pushRegisterFalse(requestVo.getId(),requestVo.getPatientName(),requestVo.getHospitalName() + " " +requestVo.getDepartmentName(), requestVo.getDoctorName()+"("+requestVo.getTitle()+")", visitTimeStr + " " + requestVo.getVisitPart(), requestVo.getHospitalAddress(), "以当天取号顺序为主，取号时间为：上午：8:00-10:00、下午：13:00-15:00、晚上：18：00-19:00",url);
        }

        log.info("短信数据\n：{}",String.valueOf(jsonObject));
        boolean sendRes = false;
        try {
            if(requestVo.getStatus() == RegisterEnum.SUCCESS.getCode()){     // 挂号成功
                sendRes = DySendMsg.sendSms(requestVo.getPatientMobile(),jsonObject, DySmsEnum.REGISTER_NOTICE);
            }else if(requestVo.getStatus() == RegisterEnum.FAIL.getCode()){  // 挂号失败
                sendRes = DySendMsg.sendSms(requestVo.getPatientMobile(),jsonObject, DySmsEnum.REGISTER_FAIL_NOTICE);
            }
        } catch (ClientException e) {
            e.printStackTrace();
        }

        if(sendRes){
            //【二】更新挂号状态
            DoctorRegisterRecord doctorRegisterRecord = doctorRegisterRecordService.getById(requestVo.getId());
            doctorRegisterRecord.setStatus(requestVo.getStatus());
            doctorRegisterRecord.setExamineTime(new Date());
            doctorRegisterRecord.setFailReason(requestVo.getFailReason());
            boolean recordRes = doctorRegisterRecordService.updateById(doctorRegisterRecord);
            if(!recordRes){
                return org.jeecg.common.api.vo.Result.error("处理失败，请稍后重试！");
            }

            return org.jeecg.common.api.vo.Result.ok("处理成功！");
        }else{
            return org.jeecg.common.api.vo.Result.error("短信发送失败，请稍后重试！");
        }
    }

    @PostMapping(value = "/refound")
    @Transactional(rollbackFor = Exception.class)
    public org.jeecg.common.api.vo.Result<?> refound(@RequestBody PrePayOrderRequestVo request,
                                                     HttpServletRequest req, HttpServletResponse response ) throws Exception{

         //获取当前时间
        Date nowDate = new Date();  //当前时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        calendar.getTime();
        String yersDay = df.format(calendar.getTime());
        String yesTime = yersDay + " 18:00";
        date=sdf.parse(yesTime);
        if(nowDate.compareTo(date)<0){
            return org.jeecg.common.api.vo.Result.ok("就诊前一天18:00后，不支持取消预约！");
        }
        String patientId = doctorRegisterRecordService.getById(request.getRegisterRecordId()).getPatientId();
        LambdaQueryWrapper<WxUserinfo> query = Wrappers.lambdaQuery();
        query.eq(WxUserinfo::getOpenid,request.getOpenid());
        log.info(request.getOpenid());
        WxUserinfo wxUserinfo = wxUserinfoService.getOne(query); //获取微信用户
        RegisterPayOrder payOrder = new RegisterPayOrder();
        payOrder.setDoctorId(request.getDoctorId());
        payOrder.setRelationId(request.getRegisterRecordId());
        payOrder.setStatus(RegisterEnum.OPERATE.getCode());
        payOrder.setPatientId(patientId);
        RegisterPayOrder registerPayOrder = registerPayOrderService.getByRelationId(payOrder);

        //生成退款申请记录
        RegisterRefoundAudit registerRefoundAudit = new RegisterRefoundAudit();
        registerRefoundAudit.setOpenid(request.getOpenid());
        registerRefoundAudit.setRegisterPayOrderId(registerPayOrder.getId());
        registerRefoundAudit.setStatus(0);
        registerRefoundAudit.setDoctorId(request.getDoctorId());
        registerRefoundAudit.setRelationId(request.getRegisterRecordId());

        //获取医生信息
        Doctor doctorInfo = doctorService.getById(request.getDoctorId());
        registerRefoundAudit.setDoctorName(doctorInfo.getName());

        //患者信息
        registerRefoundAudit.setRequestTime(new Date());
        registerRefoundAudit.setNickName(wxUserinfo.getNickname());



        RegisterPatient patientInfo = registerPatientService.getById(patientId);
        registerRefoundAudit.setMobile(patientInfo.getMobile());
        registerRefoundAudit.setPatientName(patientInfo.getName());
        registerRefoundAudit.setIdCard(patientInfo.getIdCard());
        registerRefoundAuditService.save(registerRefoundAudit);

//        //更新订单状态
//        registerPayOrder.setStatus(3);
//        registerPayOrder.setOrderType(2);
//        registerPayOrderService.updateById(registerPayOrder);
//        //释放号源
        String relationId = registerPayOrder.getRelationId();
        DoctorRegisterRecord doctorRegisterRecord = doctorRegisterRecordService.getById(relationId);
        doctorRegisterRecord.setStatus(RegisterEnum.REFOUD.getCode());
        doctorRegisterRecordService.updateById(doctorRegisterRecord);
        String departmentName = dicBeGoodAtService.getById(doctorInfo.getDepartment()).getName(); //科室名称
        String departEnd = departmentName.substring(departmentName.length() - 1); //“xxx科室”的最后一个字
        String depart = "";
        if (departEnd.equals("科")) {
            depart = departmentName.substring(0, departmentName.length() - 1);  //去除"xxx科室"的最后一个字
        } else {
            depart = departmentName;
        }
        //医院名称
        String hospitalName = "北京正中堂中医医院";
        //患者信息
        RegisterPatient registerPatient = registerPatientService.getById(doctorRegisterRecord.getPatientId());
//        wxRefundService.refundNew(registerPayOrder.getAmount()+"",registerPayOrder.getThirdOrderCode());
        DoctorRegister doctorRegister = doctorRegisterService.getById(doctorRegisterRecord.getDoctorRegisterId());
        //处理挂号日期
        Date visitTime = new SimpleDateFormat("yyyy-MM-dd").parse(doctorRegister.getVisitTime());
        String visitTimeStr = new SimpleDateFormat("yyyy年MM月dd日").format(visitTime);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name_1",patientInfo.getName());  //患者姓名
        jsonObject.put("hospital_ment",hospitalName + " " +depart); //xxx医院xxx科
        jsonObject.put("name_title",doctorInfo.getName()+"("+doctorInfo.getTitle()+")");  //xx医生xx职位
        jsonObject.put("date_part",visitTimeStr + " " + doctorRegister.getVisitPart());   //xx时间xx号
        jsonObject.put("num",doctorRegisterRecord.getVisitNum());
        jsonObject.put("patient_p","电话："+registerPatient.getMobile());
        log.info(String.valueOf(jsonObject));
        List<DoctorRegisterOperate> operateList = doctorRegisterOperateService.operateList();
        try {
            //通知运营人员
            for(DoctorRegisterOperate doctorRegisterOperate:operateList){
                DySendMsg.sendSms(doctorRegisterOperate.getPhone(),jsonObject, DySmsEnum.REGISTER_CANCEL_OPERATE_NOTICE);
            }
        } catch (ClientException e) {
            e.printStackTrace();
        }
//        wxRefundService.refundNew(registerPayOrder.getAmount()+"",registerPayOrder.getThirdOrderCode());
        return org.jeecg.common.api.vo.Result.ok("取消预约成功！");
    }


    private Pair<Boolean,String> orderPreCheck(OrderInfo orderInfo, String doctorId){
        if (Objects.isNull(orderInfo)){
            return Pair.of(false,"订单不存在");
        }
        if (!StringUtils.equals(doctorId, orderInfo.getDoctorId())){
            return Pair.of(false,"您无权修改此订单");
        }
        return Pair.of(true,null);
    }

}
